import * as React from 'react';
import { Select, Spin } from 'antd';
import { SelectProps,SelectValue } from 'antd/es/select';
import { QuestionCircleOutlined } from '@ant-design/icons';
const { Option } = Select;
import debounce from 'lodash/debounce';

export interface AutoSelectProps extends SelectProps<SelectValue>{
  fetchOptions: (search: string) => Promise<any[]>;
  searchTimeout?: number;
}

export default ({ fetchOptions, searchTimeout = 400, ...props }: AutoSelectProps) => {
  const [loading, setLoading] = React.useState(false);
  const [options, setOptions] = React.useState<any>([]);
  // const [selectValue] = React.useState(props.value);
  const [selectValue, setSelectValue] = React.useState(props.value);
  const queryDynamicOption = debounce((search: any) => {
    setLoading(true);
    fetchOptions(search).then((options) => {
      setOptions(options);
    }).finally(() => {
      setLoading(false);
    });
  }, searchTimeout);
  return (
    <Select
      labelInValue
      showSearch
      filterOption={false}
      notFoundContent={loading ? <Spin size="small"/> : '请输入有效关键字查询'}
      value={selectValue}
      className={props.className}
      style={props.style}
      suffixIcon={<QuestionCircleOutlined />}
      onSearch={queryDynamicOption}
      placeholder={props.placeholder}
      // onChange={props.onChange}
      onChange={(values, option) => {
        setSelectValue(values);
        if (props.onChange) {
          props.onChange(values, option);
        }
      }}
      mode={props.mode}
    >
      {options.map((item: any, index: any) => <Option key={`key_${props.id}_${index}`} value={item.value}>{item.label}</Option>)}
    </Select>
  );
}
